#include "BlockQueue.hpp"
#include "Task.hpp"
#include <unistd.h>
#include <ctime>
void *Consumer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while(true)
    {
        //消费
        Task task=bq->pop();
        // task.run();
        task();
        std::cout<<"处理任务: "<<task.GetTask()<<" 运算结果: "<<task.GetResult()<<", pthread id: "<<pthread_self()<<std::endl;
    }
}
void *Producer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    int x=10,y=20;
    int len = opers.size();
    while(true)
    {
        // 模拟生产数据
        int data1=rand()%10+1;
        usleep(10);
        int data2=rand()%10;
        char op=opers[rand()%len];
        Task task(data1,data2,op);
        bq->push(task);
        std::cout<<"生产了一个任务:"<< task.GetTask() << ", pthread id: "<<pthread_self()<<std::endl;
        //usleep(100000);
    }
}

int main()
{
    srand((unsigned int)time(nullptr));
    //BlockQueue<int> *bq = new BlockQueue<int>();
    BlockQueue<Task> *bq = new BlockQueue<Task>();

    pthread_t c[3], p[5];
    for(int i=0;i<3;i++){
        pthread_create(c+i, nullptr, Consumer, bq);
    }
    for(int i=0;i<5;i++){
        pthread_create(p+i, nullptr, Producer, bq);
    }

    // 单生产，单消费
    // pthread_t c, p;
    // pthread_create(&c, nullptr, Consumer, bq);
    // pthread_create(&p, nullptr, Producer, bq);
    // pthread_join(c, nullptr);
    // pthread_join(p, nullptr);

    for(int i=0;i<3;i++) {
        pthread_join(c[i], nullptr);
    }
    for(int i=0;i<5;i++) {
        pthread_join(p[i], nullptr);
    }
    delete bq;
    return 0;
}
